#include "mainchat.h"
#include "ui_mainchat.h"

#include <QHostAddress>

mainchat::mainchat(QWidget *parent ,QString name) :
    QWidget(parent),
    ui(new Ui::mainchat)
{
    ui->setupUi(this);
    myname = name;



    m_tcp = new QTcpSocket(this);
    connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
        QByteArray data = m_tcp->readAll();
        ui->recordmsg->append(data);
    });

    connect(m_tcp,&QTcpSocket::disconnected,this,[=](){
        m_tcp->close();
        //m_tcp->deleteLater();
        ui->recordmsg->append("服务器已断开连接......");
        //ui->btnlink->setDisabled(false);
    });

    connect(m_tcp,&QTcpSocket::connected,this,[=](){
        ui->recordmsg->append("已连接到服务器，等待对方连接......");
        //ui->btnlink->setDisabled(true);
    });

    ui->ipedit->hide();
    ui->portedit->hide();
    ui->me->hide();
}

void mainchat::closeEvent(QCloseEvent *)
{
    emit this->closechat();
}

mainchat::~mainchat()
{
    delete ui;
}

void mainchat::on_btnsend_clicked()
{
    QString msg = ui->sendmsg->toPlainText();
    m_tcp->write(msg.toUtf8());
    ui->recordmsg->append("用户 'my' say："+msg);
}

void mainchat::on_btnlink_clicked()
{
    QString ip = ui->ipedit->text();
    unsigned short port = ui->portedit->text().toUShort();
    m_tcp->connectToHost(QHostAddress(ip),port);
    QString relationship = ui->me->text()+"#"+myname;
    m_tcp->write(relationship.toUtf8());

}

void mainchat::getipData(QString data)
{
    ui->ipedit->setText(data);
}

void mainchat::getportData(QString data)
{
    ui->portedit->setText(data);
}

void mainchat::getmyname(QString data)
{
    ui->me->setText(data);
}
